package com.movie.service.Impl;

import com.movie.beans.Const.Const;
import com.movie.beans.LoginInfo;
import com.movie.beans.SysUser;
import com.movie.dao.LoginDAO;
import com.movie.service.LoginService;
import com.movie.service.RecordService;
import com.movie.service.SysPasswordService;
import com.movie.service.UserService;
import com.movie.utils.DateUtils;
import com.movie.utils.ShiroUtil;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private LoginDAO loginDAO;

    @Resource
    private SysPasswordService passwordService;

    @Resource
    private UserService userService;

    @Resource
    private RecordService recordService;
    public SysUser login(String username, String password){
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            throw new UnknownAccountException("用户名或密码不能为空");
        }
        SysUser u=loginDAO.selectUserByLoginName(username);
        LoginInfo loginInfo = new LoginInfo();
        if (u == null)
        {
            loginInfo.setLoginName(username);
            loginInfo.setMsg("用户不存在");
            recordLoginInfo(loginInfo);
            throw new UnknownAccountException();
        }
        if(u.getStatus().equals(Const.STATUS_FORBIDDEN)){
            loginInfo.setLoginName(u.getLoginName());
            loginInfo.setMsg("用户状态为禁止，不可登录");
            loginInfo.setStatus(u.getStatus());
            recordLoginInfo(loginInfo);
            throw new DisabledAccountException();
        }
        if(!passwordService.matches(u, password)){
            loginInfo.setLoginName(u.getLoginName());
            loginInfo.setMsg("密码错误");
            loginInfo.setStatus(u.getStatus());
            recordLoginInfo(loginInfo);
            throw new IncorrectCredentialsException();
        }
        loginInfo.setLoginName(u.getLoginName());
        loginInfo.setMsg("登录成功");
        loginInfo.setStatus(u.getStatus());

        recordLoginInfo(loginInfo);
        recordLogin(u);
        return u;
    }

    @Override
    public List<Long> selectUserIds() {
        return loginDAO.selectUserIds();
    }

    private void recordLogin(SysUser u){
        u.setLoginIp(ShiroUtil.getIp());
        u.setLoginDate(DateUtils.getNowDate());
        userService.updateUser(u);
    }

    private void recordLoginInfo(LoginInfo loginInfo){
        loginInfo.setLoginTime(DateUtils.getNowDate());
        loginInfo.setIpAddr(ShiroUtil.getIp());
        recordService.insert(loginInfo);
    }
}
